<template>
	<div ref="chartView" :style="{ height, width }"></div>
</template>

<script setup lang="ts" name="BaseChart">
import * as echarts from "echarts";
import { dayjs } from "element-plus";
import { useEcharts } from "@/hooks/useEcharts";
import { ECOpts, ECSeries } from "./lib/chart-opts";
import { randomVal } from "@/utils/util";
import { DataChart } from "./interface";
import { ComponentInternalInstance, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const seriesTemplate: DataChart.SerieOpts = { ...ECSeries[0] };
const props = defineProps({
	example: {
		type: Boolean,
		default() {
			return false;
		}
	},
	height: {
		type: String,
		default() {
			return "100%";
		}
	},
	width: {
		type: String,
		default() {
			return "calc(100% - 32px)";
		}
	},
	title: {
		type: String,
		default() {
			return "";
		}
	},
	type: {
		type: String,
		default() {
			return "line";
		}
	},
	showZoom: {
		type: Boolean,
		default() {
			return false;
		}
	},

	queryData: {
		type: Object,
		default: () => {}
	},
	dateType: {
		type: String,
		default() {
			return "";
		}
	},
	chartTitle: {
		type: String,
		default() {
			return "";
		}
	},
	chartSubTitle: {
		type: String,
		default() {
			return "";
		}
	}
});
// watch(
//   () => props.type,
//   (nval, oval) => {
//     seriesTemplate.type = props.type;
//     data.opts.series.map((item) => {
//       item.type = seriesTemplate.type;
//     });
//     randerChart();
//   }
// );

const data = reactive<any>({
	dataList: [],
	opts: { ...ECOpts }
});
delete data.opts.legend;

//echarts容器
const chartView = ref();

let myChart: echarts.ECharts;
onMounted(() => {
	myChart = echarts.init(chartView.value);
	if (props.example) {
		randerChart();
	}
});
const initChart = () => {
	if (myChart) {
		//如果已经初始化销毁当前echart
		myChart.dispose();
	}
	// 初始化echarts;
	myChart = echarts.init(chartView.value);
	seriesTemplate.type = props.type;
	//是否显示x轴滚动
	if (props.showZoom) {
		data.opts.dataZoom = [
			{
				orient: "horizontal",
				show: true, //控制滚动条显示隐藏
				realtime: true, //拖动滚动条时是否动态的更新图表数据
				start: 0, //滚动条开始位置（共100等份）
				end: 100 //滚动条结束位置
			}
		];
	}

	window.addEventListener("resize", echartsResize);
};

const echartsResize = () => {
	myChart && myChart.resize();
};

const randerChart = () => {
	//无数据，填充模拟数据
	let category: string[] = [];
	let seriesGroup = {};
	if (props.example && data.dataList.length == 0) {
		let day = dayjs().date();
		let maxDay = dayjs().daysInMonth();
		let index = 1;
		while (index <= maxDay) {
			let name = index + "日";
			let val;
			if (index <= day) {
				val = randomVal(100, 200, 1)[0];
			}

			let item: DataChart.DataInfo = { time: name, value: val };
			_setSeries(item, category, seriesGroup);
			index++;
		}
	} else {
		data.dataList.forEach((item: DataChart.DataInfo) => {
			_setSeries(item, category, seriesGroup);
		});
	}
	let legend = {};
	if (data.opts.legend) {
		legend = { ...ECOpts.legend, ...data.opts.legend };
	} else {
		legend = {
			...ECOpts.legend,
			orient: "horizontal",
			top: "20",
			x: "center",
			align: "left"
		};
	}

	if (props.type == "pie") {
		legend = {
			...ECOpts.legend,
			orient: "vertical",
			x: "right",
			y: "center"
		};
	}
	if (props.chartTitle) {
		data.opts.title.show = true;
		data.opts.title.text = props.chartTitle;
	}
	if (props.chartSubTitle) {
		data.opts.title.subtext = props.chartSubTitle;
	}
	if (data.dataList?.[0]?.unit) {
		data.opts.tooltip.formatter = `{b} <br/> {a}: {c}${data.dataList?.[0].unit}`;
		data.opts.yAxis[0].axisLabel.formatter = `{value}${data.dataList?.[0].unit}`;
	}
	data.opts.legend = legend;
	data.opts.yAxis[0].axisLine.show = props.type != "pie";
	data.opts.xAxis[0].axisLine.show = props.type != "pie";
	data.opts.xAxis[0].data = props.type != "pie" ? category : [];
	data.opts.series = Object.values(seriesGroup);

	useEcharts(myChart, data.opts);
};

function _setSeries(dataInfo: DataChart.DataInfo, category: string[], seriesGroup: DataChart.SeriesGroup) {
	//横轴
	if (!category.includes(dataInfo.time)) {
		category.push(dataInfo.time);
	}
	let val = dataInfo.value;

	//按group封装多组series
	let seriesName = dataInfo.group || "数值";
	if (!seriesGroup[seriesName]) {
		let serieOpts: DataChart.SerieOpts = { ...seriesTemplate };

		//多个series时，去掉区域效果
		if (Object.keys(seriesGroup).length > 0) {
			serieOpts.lineStyle = {};
			serieOpts.areaStyle = {};
			serieOpts.itemStyle = {};
		}
		seriesGroup[seriesName] = { ...serieOpts, name: seriesName, data: [] };
	}
	if (props.type == "pie") {
		seriesGroup[seriesName].areaStyle = {};
		seriesGroup[seriesName].data.push({ value: val, name: dataInfo.time });
	} else {
		seriesGroup[seriesName].data.push(val);
	}
}

const resize = () => {
	if (myChart) {
		myChart.resize();
	}
};
/**
 * 设置图表数据
 * @param dataList 数据列表
 * @param opts 图表配置项, from src/components/chart/lib/chart-opts.js
 * example dataList = [
 * {time:'2022-07-01',value:100,group:'rain',unit:"%"}
 * {time:'2022-07-02',value:200,group:'rain',unit:"%"}
 * {time:'2022-07-01',value:100,group:'flow',unit:"%"}
 * {time:'2022-07-02',value:100,group:'flow',unit:"%"}
 * ]
 */
const setData = (dataList: DataChart.DataList, opts?: echarts.EChartsOption) => {
	initChart();
	data.dataList = dataList.dataList || [];
	if (opts) {
		data.opts = { ...data.opts, ...opts };
	}

	if (data.dataList.length) {
		randerChart();
	} else {
		let option = {
			title: {
				text: " {a|}",
				x: "center",
				y: "center",
				subtext: props.chartTitle + proxy?.$t("basechart.subtext.nodata"),
				itemGap: -20,
				textStyle: {
					rich: {
						a: {
							color: "#999",
							fontSize: "16",
							height: 80,
							width: 160,
							backgroundColor: {
								image:
									""
							}
						}
					}
				},
				subtextStyle: {
					fontSize: 16
				}
			}
		};
		useEcharts(myChart, option);
	}
};
const setChart = (opts: echarts.EChartsOption) => {
	useEcharts(myChart, opts);
};
defineExpose({ initChart, setData, setChart, resize });
</script>
